/**
 * @funcion : http调用
 * Created by ZY on 2017/08/25
 */

let httpConcurrency = 0,
  http = require('http'),
  errCode = require('../../conf/errorCode'),
  util = require('../helper/util');

const HTTP_AGENT = new http.Agent({
  keepAlive: true,
  maxSockets: 30,
  maxFreeSockets: 10,
});
// get请求
function readHttp(taskObj, callback) {
  if (taskObj.hostname && taskObj.pathNQs) {
    ++httpConcurrency;
    // http
    var req = http.get(
      {
        hostname: taskObj.hostname,
        path: taskObj.pathNQs,
        port: taskObj.port || '80',
        agent: taskObj.agent || HTTP_AGENT,
      },
      res => {
        res.setEncoding('utf8');
        if (res.statusCode == 200) {
          var newData = '';

          res.on('data', chunk => {
            newData += chunk;
          });
          res.on('end', () => {
            --httpConcurrency;
            try {
              newData = JSON.parse(newData);
              callback(null, newData);
            } catch (err) {
              callback(
                util.genCode(taskObj.apiNo, errCode.INVALID_JSON_ERROR),
                null,
              );
            }
          });
        } else {
          callback(
            util.genCode(taskObj.apiNo, errCode.STATUS_CODE_ERROR),
            null,
          );
        }
      },
    );
    req.on('socket', socket => {
      socket.setTimeout(5 * 1000);
    });
    req.on('error', err => {
      callback(util.genCode(taskObj.apiNo, errCode.SYSTEM_ERROR), null);
      --httpConcurrency;
    });
  } else {
    callback(util.genCode(taskObj.apiNo, errCode.INVALID_FORMAT_ERROR), null);
  }
}

exports.get = readHttp;
